import Vue from 'vue';

function setTitle(el) {
  const curStyle = window.getComputedStyle(el, '');
  const textSpan = document.createElement('span');

  // 确保与当前样式相同
  textSpan.style.fontSize = curStyle.fontSize;
  textSpan.style.fontWeight = curStyle.fontWeight;
  textSpan.style.fontFamily = curStyle.fontFamily;

  document.body.appendChild(textSpan);
  textSpan.innerHTML = el.innerText;

  // console.log(textSpan.offsetWidth, el.offsetWidth);
  if (textSpan.offsetWidth >= el.offsetWidth) {
    el.style.overflow = 'hidden';
    el.style.textOverflow = 'ellipsis';
    el.style.whiteSpace = 'nowrap';

    el.setAttribute('title', el.innerText);
    // el.onmouseenter = function() {
    //   console.log('超出啦');
    //   el.setAttribute('title', el.innerText);
    // };

    // el.onmouseleave = function() {
    //   el.removeAttribute('title');
    // };
  }
  document.body.removeChild(textSpan);
}
// 自定义指令
export const showTips = Vue.directive('showTips', {
  inserted(el) {
    setTitle(el, 'bind');
  },
  componentUpdated(el) {
    setTitle(el, 'componentUpdated');
  }
});
